package com.atguigu.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.gulimall.member.dao.MemberLevelDao;
import com.atguigu.gulimall.member.entity.MemberLevelEntity;
import com.atguigu.gulimall.member.exception.PhoneExistException;
import com.atguigu.gulimall.member.exception.UserNameExistException;
import com.atguigu.gulimall.member.vo.MemberLoginVo;
import com.atguigu.gulimall.member.vo.MemberRegisterVo;
import com.atguigu.gulimall.member.vo.SocialUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.member.dao.MemberDao;
import com.atguigu.gulimall.member.entity.MemberEntity;
import com.atguigu.gulimall.member.service.MemberService;


@Service("memberService")
@Slf4j
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Autowired
    MemberLevelDao memberLevelDao;

    @Override
    public void regist(MemberRegisterVo memberRegisterVo) {
        MemberEntity member = new MemberEntity();
        //0。检查邮箱和手机号/用户名是否唯一
        checkPhoneUnique(memberRegisterVo.getPhone());
        checkUsernameUnique(memberRegisterVo.getUserName());

        //1.设置默认会员等级
        MemberLevelEntity memberLevelEntity = memberLevelDao.selectDefaultMemberLevel();
        member.setLevelId(memberLevelEntity.getId());

        //2.前端传递了的信息
        member.setUsername(memberRegisterVo.getUserName());
        member.setMobile(memberRegisterVo.getPhone());
        // 密码要加密存储
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        member.setPassword(bCryptPasswordEncoder.encode(memberRegisterVo.getPassword()));

        // 3. 其他的默认信息
        member.setCity("湖南 长沙");
        member.setCreateTime(new Date());
        member.setStatus(0);
        member.setNickname(memberRegisterVo.getUserName());
        member.setBirth(new Date());
        member.setEmail("xxx@gmail.com");
        member.setGender(1);
        member.setJob("JAVA");
        baseMapper.insert(member);
        log.info("用户注册：{}", member);
    }

    @Override
    public void checkPhoneUnique(String phone) {
        Integer cnt = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (cnt > 0) {
            throw new PhoneExistException();
        }
    }

    @Override
    public void checkUsernameUnique(String username) {
        Integer cnt = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", username));
        if (cnt > 0) {
            throw new UserNameExistException();
        }
    }

    @Override
    public MemberEntity login(MemberLoginVo memberLoginVo) {
        MemberEntity memberEntity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().
                eq("username", memberLoginVo.getLoginacct()).or().eq("mobile", memberLoginVo.getLoginacct()));
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if (memberEntity == null) {
            return null;
        } else {
            boolean matches = encoder.matches(memberLoginVo.getPassword(), memberEntity.getPassword());
            return matches ? memberEntity : null;
        }
    }

    @Override
    public MemberEntity login(SocialUser socialUser) throws Exception {
        //注册与登录双重逻辑
        MemberEntity member = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", socialUser.getUid()));
        if (member != null) {
            //已经注册过，关联信息
            MemberEntity update = new MemberEntity();
            update.setSocialUid(member.getSocialUid());
            update.setAccessToken(socialUser.getAccessToken());
            update.setExpiresIn(socialUser.getExpiresIn());

            baseMapper.updateById(update); //只会更新传递的值，为null的属性不更新

            //更新最新一輪的token和失效時間
            member.setAccessToken(socialUser.getAccessToken());
            member.setExpiresIn(socialUser.getExpiresIn());
            return member;
        } else {
            //注册新的用户
            MemberEntity memberEntity = new MemberEntity();
            //查询当前用户的信息
            Map<String, String> map = new HashMap<>();
            map.put("access_token", socialUser.getAccessToken());
            map.put("uid", socialUser.getUid());
            HttpResponse userResponse = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<>(), map);
            if (userResponse.getStatusLine().getStatusCode() == 200) {
                String json = EntityUtils.toString(userResponse.getEntity());
                // 这个JSON对象什么样的数据都可以直接获取
                JSONObject jsonObject = JSON.parseObject(json);
                log.info("从微博获取来的用户信息：{}", json);
                memberEntity.setNickname(jsonObject.getString("name"));
                memberEntity.setUsername(jsonObject.getString("name"));
                memberEntity.setGender("m".equals(jsonObject.getString("gender"))?1:0);
                memberEntity.setCity(jsonObject.getString("location"));
                memberEntity.setJob("自媒体");
                memberEntity.setEmail(jsonObject.getString("email"));
                memberEntity.setHeader(jsonObject.getString("profile_image_url"));
                memberEntity.setStatus(0);
                memberEntity.setCreateTime(new Date());
                memberEntity.setBirth(new Date());
                memberEntity.setLevelId(1L);
                memberEntity.setSign("因为有寂寞配着哥");
                memberEntity.setSocialUid(socialUser.getUid());
                memberEntity.setAccessToken(socialUser.getAccessToken());
                memberEntity.setExpiresIn(socialUser.getExpiresIn());
            }

            baseMapper.insert(memberEntity);

            return memberEntity;
        }
    }

}